#define _CRT_SECURE_NO_WARNINGS 1
#include"List.h"
ListNode* Listinit()
{
	ListNode* phead = BuyListNode(-1);
	phead->next = phead;
	phead->prev = phead;
	return phead;
}
void  LTPushBack(ListNode* phead,SLDataType x)
{
	assert(phead);
	/*LTNode* newnode = BuyListNode(x);
	LTNode* tail = phead->prev;
	tail->next = newnode;
	newnode->prev = tail;
	newnode->next = phead;
	phead->prev = phead;*/
	LTInsert(phead, x);


}
ListNode* ListCreate()
{
	ListNode* phead = Listinit();
	return phead;
}

void  LTPushFront(ListNode* phead, SLDataType x)
{
	assert(phead);
	/*LTNode* newnode = BuyListNode(x);
	newnode->next = phead->next;
	phead->next->prev = newnode;
	phead->next = newnode;
	newnode->prev = phead;*/
	LTInsert(phead, x);

}

void  LTPopFront(ListNode* phead)
{
	assert(phead);
	assert(phead->next != phead);
	/*LTNode* first = phead->next;
	LTNode* second = first->next;
	free(first);
	phead->next = second;
	second->prev = phead;*/
	LTErase(phead->next);

}
void  LTPopBack(ListNode* phead)
{
	assert(phead);
	assert(phead->next != phead);
	/*LTNode* tail = phead->prev;
	tail->prev->next = phead;
	phead->prev = tail->prev;
	free(tail);*/
	LTErase(phead->prev);

}
void SLPrint(ListNode* phead)
{
	assert(phead);
	ListNode* cur = phead->next;
	while (cur!=phead)
	{
		printf("%d ", cur->data);
		cur = cur->next;
	}
	printf("\n");
}
ListNode* BuyListNode(SLDataType x)
{
	ListNode* newnode = (ListNode*)malloc(sizeof(ListNode));
	if (newnode == NULL)
	{
		perror("malloc fail");
		exit(-1);
	}
	newnode->data = x;
	newnode->next = NULL;
	newnode->prev = NULL;
	return newnode;

}

void  LTInsert(ListNode* pos, SLDataType x)
{
	assert(pos);
	ListNode* prev = pos->prev;
	ListNode* newnode = BuyListNode(x);
	prev->next = newnode;
	newnode->prev = prev;
	newnode->next = pos;
	pos->prev = newnode;
}

void  LTErase(ListNode* pos)
{
	assert(pos);
	ListNode* prev = pos->prev;
	ListNode* next = pos->next;
	free(pos);
	prev->next = next;
	next->prev = prev;
}

ListNode* LTFind(ListNode* phead, SLDataType x)
{
	assert(phead);
	ListNode* cur = phead->next;
	while (cur != phead)
	{
		if (cur->data == x)
		{
			return cur;
		}
		cur = cur->next;
	}
	return NULL;
}

void LTDestroy(ListNode* phead)
{
	assert(phead);
	ListNode* cur = phead->next;
	if (cur != phead)
	{
		ListNode* next = cur->next;
		free(cur);
		cur = next;
	}
	free(phead);
}

bool LTEmpty(ListNode* phead)
{
	assert(phead);
	return phead->next == phead;
}
size_t LTSize(ListNode* phead)
{
	assert(phead);

	size_t size= 0;
	ListNode* cur = phead->next;
	while (cur != phead)
	{
		++size;
		cur = cur->next;
	}
	return size;
}



